package com.study.talk.module.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.study.talk.common.exception.BadRequestException;
import com.study.talk.common.resullt.FwResult;
import com.study.talk.common.util.JwtUtil;
import com.study.talk.common.util.RedisUtils;
import com.study.talk.common.util.SecurityUtil;
import com.study.talk.common.util.TokenUtil;
import com.study.talk.module.entity.User;
import com.study.talk.module.entity.UserInfo;
import com.study.talk.module.entity.resp.RespToken;
import com.study.talk.module.entity.vo.LoginVo;
import com.study.talk.module.entity.vo.PasswordVo;
import com.study.talk.module.entity.vo.RegisterUserVo;
import com.study.talk.module.entity.vo.UserInfoVo;
import com.study.talk.module.mapper.UserMapper;
import com.study.talk.module.service.UserInfoService;
import com.study.talk.module.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author thor
 * @since 2023-12-18
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private TokenUtil tokenUtil;

    @Resource
    private RedisUtils redisUtils;


    @Value("${jwt.expirationTime}")
    private long expiration;

    @ApiOperation("登录")
    @PostMapping("/login")
    public FwResult<RespToken> login(@RequestBody LoginVo loginVo) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", loginVo.getUsername()).eq("password", loginVo.getPassword());
        User user = userMapper.selectOne(wrapper);
        if (null == user) {
            throw new BadRequestException(404, "用户不存在或密码错误");
        }
        String token = JwtUtil.getTokenUser(user);
        redisUtils.set(token, JSONUtil.toJsonStr(user), expiration, TimeUnit.DAYS);
        Authentication authentication = tokenUtil.getTokenAuthentication(user.getUsername());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        RespToken body = new RespToken(user.getUsername(), token);
        return FwResult.ok(body, "登录成功");
    }


    @ApiOperation("用户注册")
    @PostMapping("/register")
    public FwResult<String> register(@RequestBody UserInfoVo userInfoVo) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userInfoVo.getUsername());
        if (userService.count(wrapper) > 0) {
            return FwResult.failed(422, "用户名已存在");
        }
        userService.save(new User(userInfoVo));
        userInfoVo.setUserId(userService.getOne(new QueryWrapper<User>().eq("username", userInfoVo.getUsername())).getId());
        userInfoService.save(new UserInfo(userInfoVo));
        return FwResult.ok("用户注册成功");
    }


    @ApiOperation("用户注册")
    @PostMapping("/register/simple")
    public FwResult<User> registerSimple(@RequestBody RegisterUserVo registerUserVo) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone_number", registerUserVo.getPhoneNumber());
        if (userService.count(wrapper) > 0) {
            return FwResult.failed(422, "手机号已经被注册");
        }
        userService.save(new User(registerUserVo));
        User user = userService.getOne(new QueryWrapper<User>().eq("username", registerUserVo.getUsername()));
        userInfoService.save(new UserInfo(user.getId(), user.getUsername(), user.getPhoneNumber()));
        return FwResult.ok(user);
    }


    @ApiOperation("用户修改密码")
    @PutMapping("/update/password")
    public FwResult<Boolean> updatePwd(@RequestBody PasswordVo passwordVo) {
        if (passwordVo.getOldPassword().equals(SecurityUtil.getUser().getPassword())) {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("username", SecurityUtil.getUser().getUsername());
            User user = userService.list(wrapper).get(0);
            user.setPassword(passwordVo.getNewPassword());
            userService.updateById(user);
            return FwResult.ok(true,"修改成功");
        }
        return FwResult.failed(false,"旧密码错误");
    }
}
